package boardgamer.common.client;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author garysoed
 */
public abstract class AbstractView<A extends AbstractActivity> extends SurfaceView
    implements SurfaceHolder.Callback {
  
  protected final A activity;

  protected AbstractView(A activity) {
    super(activity.getBaseContext());
    this.activity = checkNotNull(activity, "activity");

    getHolder().addCallback(this);
    setFocusable(false); // necessary for getting the touch events
  }

  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    handleLayout(holder.getSurfaceFrame());
    activity.ready();
  }

  @Override
  public void surfaceDestroyed(SurfaceHolder surfaceHolder) { }
  
  @Override
  public void surfaceCreated(SurfaceHolder holder) { }
  
  public final void draw(Canvas canvas) {
    canvas.save();

    canvas.drawColor(Color.BLACK);
    handleDraw(canvas);
    canvas.restore();
  }

  public final void update(int elapsedTime) {
    handleUpdate(elapsedTime);
  }

  @Override
  public final boolean onTouchEvent(MotionEvent event) {
    handleTouchEvent(event);

    // sleeps the touch detection process, apparently this reduces lag
    try {
      Thread.sleep(70);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    return true;
  }

  protected abstract void handleDraw(Canvas canvas);

  protected abstract void handleUpdate(int elapsedTime);
  
  protected abstract void handleLayout(Rect canvasRect);

  protected abstract void handleTouchEvent(MotionEvent event);
}
